package com.example.designpatterns.behavioral.chain;

/**
 * 具体处理者：限流处理，每分钟限制登录多少次
 *
 * @author scott
 */
public class ThrottlingMiddleware extends Middleware {

    private final int requestPerMinute;
    private int request;
    private long currentTime;
    private final static int LIMIT = 60_000;

    public ThrottlingMiddleware(int requestPerMinute) {
        this.requestPerMinute = requestPerMinute;
        this.currentTime = System.currentTimeMillis();
    }

    /**
     * 检查限定时间内的登录次数不能超过限制
     */
    @Override
    public boolean check(String email, String password) {
        if (System.currentTimeMillis() > currentTime + LIMIT) {
            request = 0;
            currentTime = System.currentTimeMillis();
        }

        request++;

        if (request > requestPerMinute) {
            System.out.println("已超出请求限制！");
            return false;
        }
        return checkNext(email, password);
    }
}